
define(['ionic'], function () {
    angular.module('BUSContacts.controllers', [])
        .controller('HomeCtrl', ['$scope', '$state', '$q', '$ionicListDelegate', '$ionicScrollDelegate', 'ContactService', 'ConnectService', 'UtilService',
            function ($scope, $state, $q, $ionicListDelegate, $ionicScrollDelegate, ContactService, ConnectService, UtilService) {
                $scope.data = {
                    contacts: [],
                    search: '',
                    pickScope: true, // true: 部门 false: 好友
                    quickCambers: [],
                    activeCamber: 'Z'
                };

                init();

                $scope.$on('$ionicView.beforeEnter', function () {
                    if (!$scope.data.pickScope) {
                        init();
                    }
                });
                var afterViewEnter = false;
                $scope.$on('$ionicView.afterEnter', function () {
                    afterViewEnter = true;
                });
                $scope.$watch('data.search', function (search) {
                    if (!afterViewEnter) {
                        return;
                    }
                    if (search === '') {
                        init();
                    } else {
                        ContactService.searchOperaters(search, !$scope.data.pickScope).then(function (contacts) {
                            var temp = {};
                            if (contacts.length === 0) {
                                temp.group = '没有找到符合条件联系人';
                            } else {
                                temp.group = '共找到' + contacts.length + '个联系人';
                            }
                            temp.items = contacts;
                            $scope.data.contacts = [temp];
                            $scope.data.activeCamber = '';
                        });
                    }
                });

                $scope.activeScope = function (pickScope) {
                    $scope.data.pickScope = pickScope;
                    init();
                };
                $scope.goDetail = function (id) {
                    $state.go('detail', {
                        userId: id,
                        source: $scope.data.pickScope
                    });
                };
                $scope.call = function (number, e) {
                    if (number === '') {
                        UtilService.tipsBottom('不存在有效的号码');
                    } else {
                        ConnectService.call(number).then(function () {}, function () {
                            u9.alert('拔打电话失败');
                        });
                    }
                    e.stopPropagation();
                };
                $scope.sendMsg = function (number, e) {
                    if (number === '') {
                        UtilService.tipsBottom('不存在有效的号码');
                    } else {
                        ConnectService.sendMsg(number).then(function () {}, function (err) {
                            if (err !== 'Message cancelled.') {
                                u9.alert('发送信息失败');
                            }
                        });
                    }
                    e.stopPropagation();
                };
                $scope.manageFriend = function (id, isAdd, e) {
                    u9.showLoading();
                    var friendId = parseInt(id, 10),
                        managerCmd = isAdd ? '添加' : '删除';
                    ContactService.managerFriends(friendId, isAdd).then(function (result) {
                        if (result) {
                            UtilService.tipsBottom(managerCmd + '好友成功');
                            if (!$scope.data.pickScope) {
                                init();
                            }
                        } else {
                            UtilService.tipsBottom(managerCmd + '好友失败');
                        }
                    }, function (error) {
                        UtilService.tipsBottom(error || (managerCmd + '好友失败'));
                    }).finally(function () {
                        u9.hideLoading();
                    });
                    e.stopPropagation();
                    $ionicListDelegate.closeOptionButtons();
                };

                function init() {
                    $q.when($scope.data.pickScope ? ContactService.getDepartmentContacts(): ContactService.getFriends()).then(function (contacts) {
                        $scope.data.contacts = contacts;
                        $ionicScrollDelegate.scrollTop();
                    }).finally(function () {
                        initQuickBar();
                    });
                }
                function initQuickBar () {
                    if ($scope.data.quickCambers.length === 0) {
                        for(var i = 65; i < 91; i++) {
                            $scope.data.quickCambers.push(String.fromCharCode(i));
                        }
                    }
                    if ($scope.data.contacts.length > 0) {
                        $scope.data.activeCamber = $scope.data.contacts[0].group;
                    } else {
                        $scope.data.activeCamber = '';
                    }
                }
            }
        ])
        .controller('DetailCtrl', ['$scope', '$stateParams', 'ContactService', 'ConnectService', 'UtilService',
            function ($scope, $stateParams, ContactService, ConnectService, UtilService) {
                $scope.data = {
                    fnVisible: false,
                    isFriend: false,
                    contact: {}
                };

                init();

                $scope.manageFriend = function () {
                    u9.showLoading();
                    var friendId = parseInt($scope.data.contact.id, 10),
                        isAdd = !$scope.data.isFriend,
                        managerCmd = isAdd ? '添加' : '删除';
                    ContactService.managerFriends(friendId, isAdd).then(function (result) {
                        if (result) {
                            UtilService.tipsBottom(managerCmd + '好友成功');
                            $scope.data.isFriend = isAdd;
                        } else {
                            UtilService.tipsBottom(managerCmd + '好友失败');
                        }
                    }, function (error) {
                        UtilService.tipsBottom(error || (managerCmd + '好友失败'));
                    }).finally(function () {
                        u9.hideLoading();
                    });
                };
                $scope.call = function (number) {
                    if (number === '') {
                        UtilService.tipsBottom('不存在有效的号码');
                        return;
                    }
                    ConnectService.call(number).then(function () {}, function () {
                        u9.alert('拔打电话失败');
                    });
                };
                $scope.sendMsg = function (number) {
                    if (number === '') {
                        UtilService.tipsBottom('不存在有效的号码');
                        return;
                    }
                    ConnectService.sendMsg(number).then(function () {}, function (err) {
                        if (err !== 'Message cancelled.') {
                            u9.alert('发送信息失败');
                        }
                    });
                };
                $scope.sendEmail = function (address) {
                    if (address === '') {
                        UtilService.tipsBottom('不存在有效的地址');
                        return;
                    }
                    var email = {
                        to: address
                    };

                    ConnectService.sendEmail(email);
                };

                function init () {
                    if ($stateParams.source === 'false') {
                        $scope.data.isFriend = true;
                        $scope.data.fnVisible = true;
                    } else {
                        ContactService.checkFriend($stateParams.userId).then(function (isFriend) {
                            $scope.data.isFriend = isFriend;
                            $scope.data.fnVisible = true;
                        }, function () {
                            $scope.data.fnVisible = true;
                        });
                    }
                    $scope.data.contact = ContactService.getContactDetail(
                        $stateParams.userId, $stateParams.source);
                }
            }
        ]);
});
